/*
 * @Author: Dannycjh 2233879049@qq.com
 * @Date: 2023-04-18 13:48:06
 * @LastEditors: Dannycjh 2233879049@qq.com
 * @LastEditTime: 2023-04-26 21:58:53
 * @FilePath: \cc-game-development-template\assets\scripts\Hall.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { _decorator, Component, dynamicAtlasManager, find, instantiate, Node, Prefab, UITransform ,macro, sys, view, Label} from 'cc';
import { App } from '../App';
const { ccclass, property } = _decorator;
import UtilTool from '../tools/UtilTool';
import { EventConst, localKey } from '../common/Common';
import { LoadMg } from '../tools/LoadMg';
import { PD } from '../player/PlayerData';
import { PageView } from 'cc';
import { setGuidePopuUp, setSettingPopuUp, showHallRecord, showHallShop, showHallTask, showHallWallet, showInvitePanel, showLuckyBall, showMinePanel, showRewardBox, showSystemNotice, showTip } from '../tools/PopuUp';
import { CLIENTMSG_SWITCH } from '../game/billiards/GameManage';
import GameRespBody from '../const/GameRespBody';
import AbstractComponent from '../base/AbstractComponent';
import wsTool from '../net/ws';
import CommConst from '../const/CommConst';
import { resources } from 'cc';
import { EndLayer5 } from '../game/billiards/mode5/EndLayer5';
import { Sprite } from 'cc';

let PAGE_SCALE = 1.2

//强制开启动态合图减少dc
macro.CLEANUP_IMAGE_CACHE = false;
dynamicAtlasManager.enabled = true;
dynamicAtlasManager.maxFrameSize = Infinity;
@ccclass('Hall')
export class Hall extends AbstractComponent {
    @property(Prefab)
    loadingBox: Prefab = null;

    @property(PageView)
    pageView : PageView = null

    @property(Node)
    viewNode : Node = null

    @property(Node)
    popu : Node = null

    // @property(Label)
    // adressLabel : Label = null

    @property(Node)
    head : Node = null

    @property(Node)
    noticeHD : Node = null // 系统公告红点

    @property(Node)
    taskHD : Node = null // 任务红点

    player: any = null;

    // 游戏模式下标索引
    private pageIndex = 0 // [0]幸运台球 [1]练习场 [2]多人对战

    onLoad() {
        UtilTool.printLog('进入首页');
        view.resizeWithBrowserSize(false);
        LoadMg.removeLoad()
        App.hallPanel = this
  
        // director.addPersistRootNode(this.node);
        //进入首页
        App.Audio.play("home");
         
        //用户信息更新
        App.Event.on(EventConst.UPDATA_USERINFO,(data)=>{
            UtilTool.printLog('用户信息更新',data);
            this.player = PD.playerInfo
            
            PD.setCoin(data.ustd)
            PD.setStarCoin(data.experienceNum)
        })

        App.Event.on(EventConst.UPDATE_SET_NICK, this.setNick, this)
        App.Event.on(EventConst.UPDATE_SET_HEAD, this.updateHead, this)
        App.Event.on(EventConst.UPDATE_STARCOIN,this.setStarCoin, this )
        App.Event.on(EventConst.UPDATE_TASK_HD,this.taskRedpoint, this )

        
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())
        LoadMg.loadPrefab = this.loadingBox;
        App.WSGameStatus = 0

        // 自动跳转到幸运台球二级界面
        if (App.isToHallFromMode1) {
            App.isToHallFromMode1 = false
            App.fightMode = App.fightMode_1
            showLuckyBall(this.viewNode)
        }
    }

    start() {
        this.setNick()
        this.updateHead()
        this.setStarCoin()

        // 设置引导
        if (PD.user.newPlayer && !App.isShowGuide) {
        // if (true && !App.isShowGuide) {
            App.isShowGuide = true
            setGuidePopuUp(this.viewNode)
        }

        // 设置公告红点
        this.reqNoticeIDList()

        // 检测断线重连
        App.Model.gameManage.checkReconnect()
    }

    /**
     * 更新星币数量
     */
    setStarCoin() {
        find("Node_top/adressbg/starLabel",this.node).getComponent(Label).string = PD.user.starCoin_str
    }

    update(deltaTime: number) {

    }

    /**
     * 更新昵称
     */
    setNick() {
        // this.adressLabel.string = UtilTool.formatNickOrAddress({"nickname":PD.user.nickname, "address":PD.user.addressUrl})
    }

    /**
     * 更新头像
     */
    updateHead() {
        let headDict = App.Scene.getHallRes("images/head")
        if (headDict["head_" + PD.user.headId]) {
            this.head.getComponent(Sprite).spriteFrame = headDict["head_" + PD.user.headId]
        }
    }

    /**
     * 更新任务红点显示
     */
    taskRedpoint(count){
        // 任务红点
        this.taskHD.active = count>0
        if (count>0){
            if (count>99) {
                find("count",this.taskHD).getComponent(Label).string = "99+"
            }
            else{
                find("count",this.taskHD).getComponent(Label).string = count + ""
            }
        }
    }


    /* 翻页回调 */
    onPaveView(event : PageView, eventType) {
        this.pageIndex = event.getCurrentPageIndex()
        for (let i = 0; i < 4; i++) {
            let sp_tip = find("view/content/page" + (i+1) + "/sp_tip",this.pageView.node)
            sp_tip.active = this.pageIndex==i
        }
        
        UtilTool.printLog("onPaveView 翻页回调", event.getCurrentPageIndex())
    }

    /* 按钮点击事件 */
    onBtnClick(event: Event, customEventData: string) {
        App.Audio.playOneShot("click")

        // 开始游戏
        if(customEventData == "start") {
            LoadMg.showLoad({type:1})
            if (this.pageIndex<0 && this.pageIndex>3) {return}

            App.fightMode = this.pageIndex + 1 // 赋值模式

            if (App.fightMode == App.fightMode_1) { // 幸运台球
                showLuckyBall(this.viewNode)
            }
            else if (App.fightMode == App.fightMode_2) { // 练习场
                App.Scene.go("game2")
            }
            else if (App.fightMode == App.fightMode_3) { // 多人对战
                if (CLIENTMSG_SWITCH) { // 走本地消息
                    App.Model.gameManage.resqGameStart(GameRespBody.GameStart_Data)
                    return
                }

                this.backToMultiSelect()
            }
            else if (App.fightMode == App.fightMode_4) { // 血流到底
                this.backToBloodSelect()
            }
        }
        // 我的
        else if (customEventData == "myBtn") { 
            showMinePanel(this.viewNode)

            /* resources.load('prefabs/game/layer5/GameEndLayer5',Prefab,(err,prefabs) =>{
                let layerNode = instantiate(prefabs);
                this.viewNode.addChild(layerNode);

                let data = {
                    "winPlayerAccount":"0x677e3dc63e330ec1963995f8548fe9eb97fb1c10",
                    "winPlayerNickname":"",
                    "losePlayerAccount":"0x4A65Ad4706AFa926bE520B2708eD1fcD30a8f8CD",
                    "losePlayerNickname":"水电费",
                    "reward":1001
                }
    
                if (PD.user.addressUrl == data.winPlayerAccount) {
                    layerNode.getComponent(EndLayer5).showView(data, 1)
                }
                else {
                    layerNode.getComponent(EndLayer5).showView(data, 2)
                }
            }) */
        }
        // 钱包
        else if (customEventData == "walletBtn") {
            showHallWallet(this.viewNode)
        }
        // 记录
        else if (customEventData == "recordBtn") {
            let node = showHallRecord(this.viewNode)
        }
        // 邀请
        else if (customEventData == "inviteBtn") {
            // showTip(App.language.getLanguageLab(86))
            showInvitePanel(this.viewNode)
        }
        // 设置
        else if (customEventData == "setBtn") {
            setSettingPopuUp(this.viewNode)
        }
        // 系统公告
        else if (customEventData == "NoticeBtn") {
            showSystemNotice(this.viewNode,this)
        }
        // 商城
        else if (customEventData == "shopBtn") {
            let node = showHallShop(this.viewNode)
        }
        // 任务
        else if (customEventData == "taskBtn") {
            let node = showHallTask(this.viewNode)
            // showRewardBox(1, 555)
        }

    }

    // 请求系统公告id列表
    reqNoticeIDList() {
        this.noticeHD.active = false
        wsTool.send({"msgCode":CommConst.Req_SYSTEM_NOTICE_ID, "languageId":App.language.languageId_default.toString(), "noLoad":true})
        .then(res =>{
            let list = res.list
            if (list && list.length>0) {
                let count = this.isHaveNoReadMessage(list)
                this.noticeHD.active = count>0
                if (count>0){
                    if (count>99) {
                        find("count",this.noticeHD).getComponent(Label).string = "99+"
                    }
                    else{
                        find("count",this.noticeHD).getComponent(Label).string = count + ""
                    }
                }
            }  
            
            // 任务红点
            this.taskRedpoint(res.dailyJobFinishNum)
        })
    }

    // 是否有未读的消息
    isHaveNoReadMessage(list):number {
        let noticeId:string =  App.Util.getLocalItem(localKey.NOTICE_ID, "")
        noticeId = noticeId + ""
        let idArr = noticeId.split(",")
        
        let count = 0
        list.forEach(value => {
            if (idArr.indexOf(value.toString()) == -1) {
                count++
            }
        });

        return count
    }

    // 点击跳转对应界面 [0]每日登录 [1]幸运台球 [2]血流成河 [3]四球开伦 [4]多人台球
    clickJumpPanel(type) {
        if (type==0) {
        }
        else if (type==1) { // [1]幸运台球
            App.fightMode = App.fightMode_1
            showLuckyBall(this.viewNode)
        }
        else if (type==2) { // [2]血流成河
            App.fightMode = App.fightMode_4
            this.backToBloodSelect()
        }
        else if (type==3) { // [3]四球开伦
            App.fightMode = App.fightMode_3
            this.backToMultiSelect()
        }
        else if (type==4) { // [4]多人台球
            App.fightMode = App.fightMode_3
            this.backToMultiSelect()
        }
    }

    onDestroy() {
        App.Event.off(EventConst.UPDATA_USERINFO)
        App.Event.off(EventConst.UPDATE_SET_NICK, this.setNick, this)
        App.Event.off(EventConst.UPDATE_STARCOIN, this.setStarCoin, this)
        App.Event.off(EventConst.UPDATE_TASK_HD, this.taskRedpoint, this)

        App.onClick.removeButtonClickEventAll()
        App.hallPanel = null
        UtilTool.printLog('Hall 已销毁');
        sys.garbageCollect()
        // assetManager.releaseAsset(this._view);
    }

}
